from django.db import models
from hdiary.injuries.models import *
from hdiary.preventions.models import *
from hdiary.middleware import threadlocals
from django.contrib.auth.models import User

class Injection(models.Model):
    date = models.DateField(auto_now_add = True)
    patient = models.ForeignKey(User, blank = True, default = None)
    inj_date = models.DateField('date injected')
    comment = models.CharField(maxlength=100, blank=True, default=None)
    def sum_of_units(self):
        sum = 0
        for asi in AmpouleSeriesInjection.objects.filter(injection=self.id):
            sum += int(asi.ampoule_series.units)*int(asi.amount)
        return sum
    def __unicode__(self):
        return unicode(self.inj_date)+" "+unicode(self.sum_of_units())
    def save(self):
        if self.patient_id is None:
            self.patient_id = threadlocals.get_current_user().id
        super(Injection, self).save()
    class Admin:
        list_display = ('inj_date','sum_of_units')
        list_filter = ['inj_date']
        date_hierarchy = 'inj_date'

class InjectionInjuryAssociation(models.Model):
    injection = models.ForeignKey(Injection, edit_inline=models.TABULAR, num_in_admin=1)
    injury = models.ForeignKey(Injury, core=True, default=None)
    def __unicode__(self):
        return unicode(self.injury)
#  class Admin:
#    pass

class InjectionPreventionAssociation(models.Model):
    injection = models.ForeignKey(Injection, edit_inline=models.TABULAR, num_in_admin=1)
    prevention = models.ForeignKey(Prevention, core=True, default=None)
    def __unicode__(self):
        return unicode(self.prevention)
#  class Admin:
#    pass

